package servlet;

import java.io.IOException;
import java.util.*;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.*;

@SuppressWarnings("serial")
public class MessageServlet extends HttpServlet {

	public MessageServlet() {
		super();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Message msg = new Message();
		String str = request.getParameter("message");
		msg.setMessage(str);
		msg.setDate(new Date());
		User curUser = (User) request.getSession().getAttribute("user");
		msg.setUser(curUser);
		ServletContext application = this.getServletContext();
		Queue<Message> messages = (Queue<Message>) application
				.getAttribute("messages");
		if (messages == null)
			messages = new LinkedList<Message>();
		if (msg.getMessage().length() != 0) {
			messages.offer(msg);
			application.setAttribute("messages", messages);
		}
		PrintWriter writer = response.getWriter();
		java.text.DateFormat format1 = new java.text.SimpleDateFormat(
				"hh:mm:ss");

		for (Message tmp : messages) {
			writer.write("<font color=\"");
			if (curUser != null
					&& curUser.getUsername()
							.equals(tmp.getUser().getUsername())) {
				writer.write("green");
			} else {
				writer.write("blue");
			}
			writer.write("\">\n");
			writer.write("<strong>" + tmp.getUser().getUsername()
					+ "</strong>&nbsp;&nbsp;");
			writer.write(format1.format(tmp.getDate()));
			writer.write("</font>\n<br />\n&nbsp;&nbsp;&nbsp;&nbsp;");
			writer.write(tmp.getMessage() + "<br />\n");

		}
		writer.flush();
		writer.close();
	}

}
